<script setup lang="ts">
import { request } from '@/api'
import { closeToast, showLoadingToast, showToast, type ActionSheetAction } from 'vant'
import { onMounted, ref } from 'vue'
import base64ToBlob from 'b64-to-blob'

const show = ref(false)
const showDateSelectBottom = ref(false)
const actions = [{ name: '相册' }, { name: '拍照' }]
const onSelectAvatar = async (item: ActionSheetAction) => {
  // 隐藏弹层
  show.value = false
  if (item.name === '相册') {
    const data = await mk.pickerPhoto()
    await onUpdateAvatar(data)
  } else if (item.name === '拍照') {
    const data = await mk.pickerCamera()
    await onUpdateAvatar(data)
  }
}

const onUpdateAvatar = async (data: string) => {
  try {
    show.value = false
    showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    const image = base64ToBlob(data, 'image/jpeg')
    const fd = new FormData()
    fd.append('file', image, Date.now() + '.jpeg')
    const res = await request.post<MkResponse<{ avatar: string }>>('member/profile/avatar', fd)
    profile.value.avatar = res.data.result.avatar

    // 修改原生侧的头像
    const user = mk.queryUser()
    user.avatar = res.data.result.avatar
    mk.updateUser(user)
    showToast({ message: '上传成功' })
  } catch (error) {
    console.log(error)
    showToast({ message: '上传失败' })
  }
}

const now = new Date()
const birthday = ref([
  now.getFullYear().toString(),
  String(now.getMonth() + 1),
  now.getDate().toString()
])

// 选择生日
const onChangeBirthday = (obj: any) => {
  profile.value.birthday = obj.selectedValues.join('-')
  showDateSelectBottom.value = false
}

// 城市列表底部弹层
const showLocationSelectBottom = ref(false)
// 调用接口获取数据
const areaColumns = ref<AreaColumns>()

// 个人信息
const profile = ref<ProfileInfo>({} as ProfileInfo)
const profession = ref<string[]>([])
onMounted(async () => {
  showLoadingToast({ message: '加载中...', duration: 0, forbidClick: true })
  // 获取个人信息
  const res = await request.get<MkResponse<ProfileInfo>>('member/profile')
  console.log('获取个人信息', res.data)

  const data = await mk.getAreaColumns()
  areaColumns.value = data
  console.log(data)

  closeToast()
  profile.value = res.data.result
  birthday.value = profile.value.birthday.split('-')
  // 5.5 取出职业给到页面
  profession.value.push(res.data.result.profession)
})

// 选择所在地
const onSelectLocation = (data: any) => {
  showLocationSelectBottom.value = false
  console.log(data.selectedValues)
  // 1.2 处理数据
  profile.value.provinceCode = data.selectedValues[0]
  profile.value.cityCode = data.selectedValues[1]
  profile.value.countyCode = data.selectedValues[2]
  const province = areaColumns.value?.province_list[data.selectedValues[0]]
  const city = areaColumns.value?.city_list[data.selectedValues[1]]
  const county = areaColumns.value?.county_list[data.selectedValues[2]]
  profile.value.fullLocation = `${province} ${city} ${county}`

  profile.value.provinceCode = data.selectedValues[0]
  profile.value.cityCode = data.selectedValues[1]
  profile.value.countyCode = data.selectedValues[2]
}

// 职业
const professionList = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' }
]
const showProfessionPopup = ref(false)
const onChangeProfession = (data: { selectedValues: string[] }) => {
  console.log(data)
  showProfessionPopup.value = false
  profile.value.profession = data.selectedValues[0]
}

// 保存加载中
const loading = ref(false)
const save = async () => {
  try {
    if (!profile.value.nickname) {
      return showToast({ message: '请输入昵称' })
    }
    loading.value = true
    await request.put('member/profile', profile.value)
    loading.value = false
    // 更新返回页面本地昵称
    const user = mk.queryUser()
    user.nickname = profile.value.nickname
    mk.updateUser(user)
    showToast({ message: '保存成功' })
  } catch (error) {
    console.log(error)
    showToast({ message: '保存失败' })
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image
        width="5rem"
        height="5rem"
        :src="profile.avatar"
        class="avatar-img"
        round
      ></van-image>
      <div class="avatar-btn" @click="show = true">更换头像</div>
    </div>

    <!-- 选择面板 -->
    <van-action-sheet
      v-model:show="show"
      :actions="actions"
      @select="onSelectAvatar"
      cancel-text="取消"
      :style="{ paddingBottom: '20px' }"
    />
    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" v-model="profile.account" readonly />
      <van-field label="昵称" placeholder="请输入昵称" v-model="profile.nickname" />
      <van-cell title="性别" class="gender">
        <van-radio-group class="van-radio-group" v-model="profile.gender">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
        </van-radio-group>
      </van-cell>
    </van-cell-group>
    <van-field
      label="生日"
      placeholder="请选择日期"
      v-model="profile.birthday"
      @click="showDateSelectBottom = true"
      readonly
    />

    <!-- 底部弹出 -->
    <van-popup v-model:show="showDateSelectBottom" position="bottom" :style="{ height: '30%' }">
      <van-date-picker
        title="选择日期"
        v-model="birthday"
        @cancel="showDateSelectBottom = false"
        @confirm="onChangeBirthday"
        :min-date="new Date('1980-01-01')"
      />
    </van-popup>
    <van-field
      label="所在地"
      @click="showLocationSelectBottom = true"
      placeholder="请选择所在地"
      v-model="profile.fullLocation"
      readonly
    />
    <van-popup v-model:show="showLocationSelectBottom" position="bottom" round>
      <van-area
        :area-list="areaColumns"
        @confirm="onSelectLocation"
        @cancel="showLocationSelectBottom = false"
      />
    </van-popup>
    <van-field
      label="职业"
      v-model="profile.profession"
      @click="showProfessionPopup = true"
      placeholder="请选择职业"
      readonly
    />
    <van-popup v-model:show="showProfessionPopup" position="bottom" round>
      <van-picker
        title="选择职业"
        v-model="profession"
        :columns="professionList"
        @confirm="onChangeProfession"
        @cancel="showProfessionPopup = false"
      />
    </van-popup>
    <!-- 底部按钮部分 -->
    <van-button
      @click="save"
      :loading="loading"
      loading-text="提交中..."
      class="submit"
      type="primary"
      round
      block
      >保存资料</van-button
    >
  </div>
</template>

<style scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

/* 默认情况下无法修改组件内容样式 .van-cell__title 是van-cell 默认的div 我们从这里使用::v-deep 深度穿透 找到它设置flex为none  */
.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
